package cn.kgc.boot.aop;

import cn.kgc.boot.annotation.MyDemo;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.UUID;

/**
 * @author XMF
 * @date 2021-06-23 10:01
 **/
@Aspect
@Slf4j
@Component
public class AnnotationLogAop {


    @Pointcut("@annotation(cn.kgc.boot.annotation.MyDemo)")
    public void logAop(){
    }

//    @Before("logAop()")
//    public void doLog(JoinPoint joinPoint){
//        LOGGER.info("日志打印");
//        LOGGER.info(joinPoint.getThis().toString());
//        LOGGER.info(joinPoint.getSourceLocation().toString());
//        LOGGER.info(joinPoint.getTarget().toString());
//        LOGGER.info(joinPoint.getKind());
//        LOGGER.info(joinPoint.getStaticPart().toString());
//        LOGGER.info(Arrays.toString(joinPoint.getArgs()));
//
//    }


    private static final String REQUEST_ID = "requestId";


    @Before("logAop()")
    public void around(JoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        MyDemo syslog = method.getAnnotation(MyDemo.class);
        System.out.println(point.getKind()); // 方法名称
        System.out.println(point.getStaticPart().getSignature().getName()); // 方法名称
        System.out.println(point.getStaticPart().getSignature().getDeclaringTypeName()); // 类名称
        System.out.println(point.getStaticPart().getSignature().getModifiers()); // 方法名称
        System.out.println(Arrays.toString(point.getArgs())); // 方法名称
        log.info(syslog.desc());
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        return checkIp(ip)
                ? ip
                : (checkIp(ip = request.getHeader("Proxy-Client-IP"))
                ? ip
                : (checkIp(ip = request.getHeader("WL-Proxy-Client-IP"))
                ? ip
                : request.getRemoteAddr()));
    }

    private static boolean checkIp(String ip) {
        return !org.springframework.util.StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip);
    }


}
